#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/timerfd.h>

int main()
{
    int timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
    if(timerfd < 0){
        std::cerr << "timerfd_create failed" << std::endl;
        return -1;
    }

    struct itimerspec itime;
    // 设置第一次超时间隔时间为 1 s
    itime.it_value.tv_sec = 1;
    itime.it_value.tv_nsec = 0;

    // 设置第一次超时后 每次超时时间间隔为 1 s
    itime.it_interval.tv_sec = 1;
    itime.it_interval.tv_nsec = 0;

    // 设置定时器
    int ret = timerfd_settime(timerfd, 0, &itime, NULL);
    if(ret < 0){
        std::cerr << "timer_settime failed" << std::endl;
        return -1;
    }
    
    // 当前这个定时器描述符每隔 1 s触发可读事件
    time_t start = time(NULL);

    while(1){
        uint64_t times;
        int ret = read(timerfd, &times, 8);
        if(ret < 0){
            std::cerr << "read failed" << std::endl;
            return -1;
        }
        printf("超时了, 距离上次超时了 %ld 次\n", times);
        std::cout << "超时次数" << times << " , 当前时间: " << time(NULL) - start << std::endl;
    }
    close(timerfd);
    return 0;
}